package com.mybatisplus.kc.controller;


import com.mybatisplus.kc.common.R;
import com.mybatisplus.kc.config.ShiroSessionListener.ShiroSessionListener;
import com.mybatisplus.kc.mapper.UserMapper;
import com.mybatisplus.kc.model.User;
import com.mybatisplus.kc.service.UserService;
import javafx.scene.control.ToolBar;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * author shish
 * Create Time 2019/1/12 14:26
 * author email shisheng@live.com
 * website www.bangnila.com
 **/
@RestController
public class ApiLoginController {
    @Autowired
    private ShiroSessionListener shiroSessionListener;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public R login(HttpServletRequest request, String username,String password, HttpServletResponse response,Boolean rememberMe, HttpSession session, Model model,String  captcha){

        //校验验证码
        //session中的验证码
         String sessionCaptcha = (String) SecurityUtils.getSubject().getSession().getAttribute(CaptchaController.KEY_CAPTCHA);
        if (null == captcha || !captcha.equalsIgnoreCase(sessionCaptcha)) {
            return R.error(700,"验证码不对！！，请刷新！！");
        }
        //对密码进行加密
        //password=new SimpleHash("md5", password, ByteSource.Util.bytes(username.toLowerCase() + "shiro"),2).toHex();
        //如果有点击  记住我
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password,rememberMe);
        //UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            //登录操作
            subject.login(usernamePasswordToken);
            //登录操作
           User user= (User) subject.getPrincipal();
          //更新用户登录时间，也可以在ShiroRealm里面做
            session.setAttribute("user", user);
            model.addAttribute("user",user);
            model.addAttribute("count",shiroSessionListener.getSessionCount());
            System.out.println(shiroSessionListener.getSessionCount());
            return R.error(100,"登陆成功！！！！！");
        } catch(Exception e) {
            //登录失败从request中获取shiro处理的异常信息 shiroLoginFailure:就是shiro异常类的全类名
            String exception = (String) request.getAttribute("shiroLoginFailure");

            if(e instanceof UnknownAccountException){
                model.addAttribute("msg","用户名或密码错误！");
            }

            if(e instanceof IncorrectCredentialsException){
                model.addAttribute("msg","用户名或密码错误！");
            }

            if(e instanceof LockedAccountException){
                model.addAttribute("msg","账号已被锁定,请联系管理员！");
            }

            //返回登录页面
            return R.error(101,"账户密码不对，请稍后再试！！！！");
        }
    }
    @RequestMapping("/register")
    public R register( User userInfo,String captcha) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String sessionCaptcha = (String) SecurityUtils.getSubject().getSession().getAttribute(CaptchaController.KEY_CAPTCHA);
        if (null == captcha || !captcha.equalsIgnoreCase(sessionCaptcha)) {
            return R.error(700,"验证码不对！！，请刷新！！");
        }
         User user=userService.findByUserName(userInfo.getUsername());//查询已经注册的账户信息
         if (user==null){
             //注册的时候加密的密码
             String newPs=new BCryptPasswordEncoder().encode(userInfo.getPassword());
             userInfo.setPassword(newPs);
             userService.insertUserInfo(userInfo);
             return R.error(100,"注册成功");
         }
        System.out.println(userInfo);
        System.out.println("已存在该用户名");
        return R.error(101,"用户存在,请输入其他用户名！！！！");

    }



}
